package com.liu.voluntary.util;


import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class SearchHttpAK {

    public static String URL = "https://api.map.baidu.com/geocoding/v3?";

    public static String AK = "lT3rqoUYzT0NYXUDAcxftTy7nLnOIrWs";

    public static String getGeocodingInfo(String address) throws Exception {
        if (address == null || address.isEmpty()) {
            throw new IllegalArgumentException("Address cannot be null or empty.");
        }

        Map<String, String> params = new LinkedHashMap<>();
        params.put("address", address);
        params.put("ak", AK);
        params.put("output", "json");

        // 构建查询字符串
        StringBuilder queryString = new StringBuilder(URL);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (queryString.length() > URL.length()) {
                queryString.append("&");
            }
            queryString.append(entry.getKey()).append("=")
                    .append(java.net.URLEncoder.encode(entry.getValue(), "UTF-8"));
        }

        // 发送HTTP GET请求并读取响应
        java.net.URL url = new URL(queryString.toString());
        HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setRequestMethod("GET");
        httpConnection.connect();

        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(httpConnection.getInputStream(), "UTF-8"))) {
            return reader.lines().collect(Collectors.joining());
        } finally {
            httpConnection.disconnect();
        }
    }
}
